#include"func.h"
using namespace std;
//do something to fd write or read
static void do_something(int connfd) {
    char rbuf[64] = {};
    //读取套接字中的数据
    ssize_t n = read(connfd, rbuf, sizeof(rbuf) - 1);
    //将read替换为recv来读取socket的数据
    //ssize_t n = recv(connfd,rbuf,sizeof(rbuf)-1);
    if (n < 0) {
        cout<<"read() error"<<endl;
        return;
    }
    printf("client says: %s\n", rbuf);
    //向socket中写入数据
    char wbuf[] = "world";
    //使用send()向socket中写入数据
    write(connfd, wbuf, strlen(wbuf));
    //send(connfd,wbuf,strlen(wbuf));
}
int main(int argc,char* argv[]){

    int fd = socket(AF_INET,SOCK_STREAM,0);
    int val = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));

    struct sockaddr_in addr = {};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(2345);        // port
    addr.sin_addr.s_addr = htonl(0);    // wildcard IP 0.0.0.0
    //绑定socket
    int rv = bind(fd, (const struct sockaddr *)&addr, sizeof(addr));
    //监听socket
    rv = listen(fd,SOMAXCONN);

    //循环接受套接字，看是否有连接进行操作了
    while (true) {
        // accept
        struct sockaddr_in client_addr = {};
        socklen_t addrlen = sizeof(client_addr);
        int connfd = accept(fd, (struct sockaddr *)&client_addr, &addrlen);
        if (connfd < 0) {
            continue;   // error
        }

        do_something(connfd);
        close(connfd);
    }
    return 0;
}

